package com.jgssp.ad.sdk.topon.adapter;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.anythink.core.api.ATInitMediation;
import com.anythink.core.api.MediationInitCallback;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

import cn.jiguang.jgssp.ADJgSdk;
import cn.jiguang.jgssp.config.ADJgInitConfig;
import cn.jiguang.jgssp.config.CustomDeviceInfoController;
import cn.jiguang.jgssp.listener.ADJgInitListener;

public class InitManager extends ATInitMediation {


    private static final String TAG = InitManager.class.getSimpleName();

    private static InitManager sInstance;
    private Handler mHandler;
    private boolean mIsOpenDirectDownload;

    private boolean mHasInit;
    private AtomicBoolean mIsIniting;
    private List<MediationInitCallback> mListeners;
    private final Object mLock = new Object();

    private InitManager() {
        mHandler = new Handler(Looper.getMainLooper());
        mIsOpenDirectDownload = false;
        mIsIniting = new AtomicBoolean(false);
    }

    public synchronized static InitManager getInstance() {
        if (sInstance == null) {
            sInstance = new InitManager();
        }
        return sInstance;
    }


    public synchronized void initSDK(Context context, Map<String, Object> serviceExtras) {
        initSDK(context, serviceExtras, null);
    }

    @Override
    public synchronized void initSDK(Context context, Map<String, Object> serviceExtras, MediationInitCallback mediationInitCallback) {
        initSDK(context, serviceExtras, true, mediationInitCallback);
    }


    public void initSDK(final Context context, Map<String, Object> serviceExtras, final boolean isAgreePrivacyStrategy, final MediationInitCallback callback) {

        if (mHasInit) {
            if (callback != null) {
                callback.onSuccess();
            }
            return;
        }

        synchronized (mLock) {

            if (mIsIniting.get()) {
                if (callback != null) {
                    mListeners.add(callback);
                }
                return;
            }

            if (mListeners == null) {
                mListeners = new ArrayList<>();
            }

            mIsIniting.set(true);
        }

        if (!serviceExtras.containsKey("app_id")) {
            callback.onFail("app_id is null");
            return;
        }

        final String appId = (String) serviceExtras.get("app_id");

        if (callback != null) {
            mListeners.add(callback);
        }

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                initJUnionAd(context, appId, isAgreePrivacyStrategy);
            }
        });
    }

    private void initJUnionAd(Context context, String appId, boolean isAgreePrivacyStrategy) {
        try {

            ADJgInitConfig initConfig = new ADJgInitConfig.Builder()
                    .appId(appId)
                    .debug(JGATInitManager.getInstance().isDebug())
                    //【慎改】是否同意隐私政策，将禁用一切设备信息读起严重影响收益
                    .agreePrivacyStrategy(JGATInitManager.getInstance().isAgreePrivacyStrategy())
                    .isCanUseLocation(JGATInitManager.getInstance().isCanUseLocation())
                    .isCanUsePhoneState(JGATInitManager.getInstance().isCanUsePhoneState())
                    .setCustomDeviceInfoController(new CustomDeviceInfoController() {
                        @Override
                        public String getOaid() {
                            return JGATInitManager.getInstance().getOaid();
                        }

                        @Override
                        public String getVaid() {
                            return JGATInitManager.getInstance().getVaid();
                        }

                        @Override
                        public String getAndroidId() {
                            return JGATInitManager.getInstance().geAndroidId();
                        }

                        @Override
                        public String getMacAddress() {
                            return JGATInitManager.getInstance().getMac();
                        }

                        @Override
                        public String getImei() {
                            return JGATInitManager.getInstance().getImei();
                        }
                    })
                    .build();

            ADJgSdk.getInstance().init(context, initConfig, new ADJgInitListener() {
                @Override
                public void onSuccess() {
                    mHasInit = true;
                    Log.i(TAG, "极光SSP初始化成功" + Thread.currentThread().getName());
                    callbackResult(true, null, null);
                }

                @Override
                public void onFailed(String s) {
                    Log.i(TAG, "极光SSP初始化失败" + Thread.currentThread().getName());
                    callbackResult(false, -1 + "", s);
                }
            });
        } catch (Throwable e) {
            callbackResult(false, "", e.getMessage());
        }
    }

    private void callbackResult(boolean success, String errorCode, String errorMsg) {
        synchronized (mLock) {
            int size = mListeners.size();
            MediationInitCallback initListener;
            for (int i = 0; i < size; i++) {
                initListener = mListeners.get(i);
                if (initListener != null) {
                    if (success) {
                        initListener.onSuccess();
                    } else {
                        initListener.onFail(errorCode + ":" + errorMsg);
                    }
                }
            }
            mListeners.clear();

            mIsIniting.set(false);
        }
    }

    @Override
    public String getNetworkName() {
        return "jgssp";
    }


    @Override
    public String getNetworkVersion() {
        try {
            return ADJgSdk.getInstance().getSdkVersion();
        } catch (Throwable e) {

        }
        return "";
    }

    private String getOaid() {
        //TODO 补充获取oaid具体方法，否则会影响广告收益
        return null;
    }

    private String getVaid() {
        //TODO 补充获取vaid具体方法
        return null;
    }
}
